package controller;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import util.DAOException;
import domain.Contact;
import domain.ContactGroup;
import domain.factory.POJOFactory;
import domain.itf.IDAOContact;

/**
 * Controller implementation for add a new {@link Contact}.
 */
@Controller
@RequestMapping("/AddGroup")
public class AddGroupController {

	@Autowired
    ServletContext servletContext;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("addGroup");
		
		return view;
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView doPost(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("main");
		
		String nameGroup = request.getParameter("nameGroup");
		ContactGroup group = POJOFactory.instance.newContactGroup(nameGroup, null);
		
		// Contacts
		String[] contacts = request.getParameterValues("contacts");

		try {
			ApplicationContext context = WebApplicationContextUtils
					.getWebApplicationContext(servletContext);

			IDAOContact daoContact = (IDAOContact) context.getBean("DAOContact");
			if (contacts != null && contacts.length > 0) {
				for (String concatId : contacts) {
					try {
						// get the contact
						Contact contact = daoContact.getById(Integer.parseInt(concatId));
						// add the new group and update database
						contact.getBooks().add(group);
						daoContact.updateContact(contact);
						
					} catch (NumberFormatException e) {}
				}
			}
			
			view.addObject("messageInfo", "You have succesful create the group.");
			
		} catch (DAOException e) {
			view.addObject("messageError", e.getMessage());
		}
		return view;
	}
}
